package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties properties;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    @SneakyThrows
    public String fileUpload(MultipartFile file) {

        //检验是否为图片联系
        BufferedImage buffer = ImageIO.read(file.getInputStream());
        //判断
        if(buffer==null){

//           throw new GuiguException(ResultCodeEnum.ARGUMENT_VALID_ERROR);
           throw new RuntimeException("不是图片类型");
        }

        //生成文件名称和目录 sph桶 2023-11-14 /ajslfkdjsalkf552222.jpg

        //生成目录
        String folderName = DateUtil.today();
        //获取后缀名
        String extName = FileUtil.extName(file.getOriginalFilename());
        //生成随机数
        String uuid = IdUtil.randomUUID();
        //生成文件名称
        String fileName=folderName+"/"+uuid+"."+extName;
        //上传图片到minio
        //mime类型
        // Upload known sized input stream.
        minioClient.putObject(
                PutObjectArgs.builder().bucket(properties.getBucketName()).object(fileName).stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());

        //返回完成路劲
        String fileUrl=properties.getEndpointUrl()+"/"+properties.getBucketName()+"/"+fileName;
        System.out.println(fileUrl);

        return fileUrl;
    }



}
